package com.jasonzhou.onetomanycontrol.room

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.jasonzhou.onetomanycontrol.base.AppContent
import com.jasonzhou.onetomanycontrol.room.entity.AdjustColor
import com.jasonzhou.onetomanycontrol.room.entity.DeviceRecord

@Database(entities = [AdjustColor::class, DeviceRecord::class], version = 2)
abstract class AppDatabase : RoomDatabase() {
    abstract fun adjustColorDao(): AdjustColorDao
    abstract fun deviceRecordDao(): DeviceRecordDao
}

/**
 * 数据库修改表升级
 */
//private class Migration1_2 : Migration(1, 2) {
//    override fun migrate(db: SupportSQLiteDatabase) {
//        db.execSQL(
//            "CREATE TABLE DeviceRecord(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, address TEXT NOT NULL, type TEXT NOT NULL, remark TEXT NOT NULL)"
//        )
//    }
//}

class RoomUtils private constructor() {
    private val database: AppDatabase by lazy {
        Room.databaseBuilder(AppContent.instance, AppDatabase::class.java, "database")
//            .addMigrations(Migration1_2())
            .build()
    }


    companion object {
        @Volatile
        private var instance: RoomUtils? = null

        fun getInstance(): RoomUtils {
            return instance ?: synchronized(this) {
                instance ?: RoomUtils().also { instance = it }
            }
        }
    }

    val userRepository: AdjustColorRepository by lazy {
        AdjustColorRepository(database.adjustColorDao())
    }

    val deviceRecordRepository: DeviceRecordRepository by lazy {
        DeviceRecordRepository(database.deviceRecordDao())
    }

}